package com.h3bpm.web.reback.service.rebackServiceImpl;

import OThinker.Common.Organization.Models.User;
import OThinker.H3.Entity.DataModel.BizObject;
import OThinker.H3.Entity.Instance.Data.InstanceData;
import com.h3bpm.base.util.AppUtility;
import com.h3bpm.web.common.utils.SqlUtil;
import com.h3bpm.web.msg.util.StringUtils;
import com.h3bpm.web.reback.controller.WritebackController;
import com.h3bpm.web.reback.service.RebackService;
import com.h3bpm.web.util.DateUtil;
import data.DataRow;
import data.DataTable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author villwang
 * @date 2020/08/27
 **/
@Service
public class RebackServiceImpl implements RebackService {

    private final static Logger logger = LoggerFactory.getLogger(RebackServiceImpl.class);

    private static String dateFormatStr = "yyyy-MM-dd";

    private static String dataSources = "EC";

    @Qualifier("secondaryJdbcTemplate")
    @Autowired
    private JdbcTemplate secondaryDataSource;
    @Override
    public int getMaxId(String tableName,String name) {
        String sql="select max("+name+") from "+tableName;
        Object obj = secondaryDataSource.queryForObject(sql, Object.class);
        //如果表中没有数据，默认最大值为1
        Integer integer = 1;
        if(obj!=null){
            integer = (Integer)obj;
        }
        return integer;
    }

    @Override
    public Boolean performSql(String sql) {
        return secondaryDataSource.update(sql)>0;
    }

    @Override
    public List<Map<String, Object>> queryForList(String sql){
        return secondaryDataSource.queryForList(sql);
    }

    @Override
    public int saveWriteBackLog(String bizObjectSchemaCode, String returnJson, String instanceId, String status) {
        String writeBackSql="insert into sys_writebackoalog (ObjectID, BizObjectSchemaCode, ReturnJson, InstanceId, CreatedTime, Status)" +
                " values ('"+ UUID.randomUUID()+"', '%s', '%s', '%s', now(), '%s')";
        if(returnJson.length()>20000){
            returnJson = returnJson.substring(0, 20000);
        }
        String sql = String.format(writeBackSql, bizObjectSchemaCode, returnJson, instanceId, status);
        return SqlUtil.doNoQuery(sql);
    }

    /**
     * 招标代理号新增申请回写
     *
     * @param instanceId
     * @return
     */
    @Override
    public boolean applicationAgencyNo(String instanceId, String workflowCode, String reportNo) {
        boolean flag = false;
        /*String insetSql = "insert into OA_yw_实施台账_招标代理管理 (ID_3177, 项目代码, 项目全局ID, 业务名称, " +
                "业务类别全局ID, 招标代理号全局ID, 标段名称 , 招标师姓名, 招标方式, 招标类别一, 招标类别二, " +
                "监管部门, 发布媒体, 其他媒体, 政府采购预算编号, 报建编号或招标编号, 标段编号或招标编码," +
                "沪合同备案网上受理编号, 招标代理号) values('%s', '%s', '%s', '%s', '%s', '%s', '%s','%s', " +
                "'%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')";*/
        String insetSql = "insert into OA_yw_实施台账_招标代理管理 (ID_3177, 项目代码, 项目全局ID, " +
                "业务类别全局ID, 业务类别, 标段名称 , 招标师姓名, 招标方式, 招标类别一, 招标类别二, " +
                "监管部门, 公告媒体, 其他媒体, 政府采购预算编号, 报建编号或招标编号, 标段编号或招标编码," +
                "沪合同备案网上受理编号, 招标代理号, 数据来源, 业务ID, 业务名称, 申请日期, 是否发布媒体) values('%s', '%s', '%s', '%s', '%s', '%s', '%s','%s', " +
                "'%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')";
        try {
            InstanceData instanceData = new InstanceData(AppUtility.getEngine(), instanceId, User.AdministratorID);
            BizObject bizObject = instanceData.getBizObject();
            //项目代码
            String projectCode = (String)bizObject.GetValue("projectCode");
            //项目全局ID
            String projectGlobalId = (String)bizObject.GetValue("projectGlobalId");
            //业务类别全局ID
            String businessCategoryId = (String)bizObject.GetValue("businessCategoryId");
            //业务类别
            String businessCategory = (String)bizObject.GetValue("businessCategory");
            //招标代理号全局ID
//            String ObjectID = bizObject.getObjectID();
            //标段名称
            String noName = (String)bizObject.GetValue("noName");
            //招标师姓名
            String tendererName = (String)bizObject.GetValue("tendererName");
            //招标方式
            String tenderMethod = (String)bizObject.GetValue("tenderMethod");
            //招标类别一
            String tenderCategory1 = (String)bizObject.GetValue("tenderCategory1");
            //招标类别二
            String tenderCategory2 = (String)bizObject.GetValue("tenderCategory2");
            //监管部门
            String regulators = (String)bizObject.GetValue("regulators");
            //发布媒体
            String publishingMedia = (String)bizObject.GetValue("publishingMedia");
            publishingMedia = publishingMedia==null ? "": publishingMedia.replace(";",",");
            //其他媒体
            String otherMedia = (String)bizObject.GetValue("otherMedia");
            //政府采购预算编号
            String governmentBudgetNo = (String)bizObject.GetValue("governmentBudgetNo");
            //沪报建编号（或招标编号）
            String constructionApplicationNo = (String)bizObject.GetValue("constructionApplicationNo");
            //沪标段号（或其他编号）
            String blocks = (String)bizObject.GetValue("blocks");
            //沪合同备案网上受理编号
            String acceptanceNumber = (String)bizObject.GetValue("acceptanceNumber");
            //招标代理号
            String biddingAgencyNo = org.apache.commons.lang3.StringUtils.isNotBlank(reportNo)?reportNo:(String)bizObject.GetValue("biddingAgencyNo");
            //业务ID
            String businessId = (String)bizObject.GetValue("businessId");
            //业务名称
//            String businessName = (String)bizObject.GetValue("businessName");
            String businessName = (String)bizObject.GetValue("noName");
            //申请日期
            String approvalDate = WritebackController.clearDefaultDate(DateUtil.format(new Date(), dateFormatStr));
            //是否发布媒体
            String publicFlag = (String)bizObject.GetValue("publicFlag");
//            int maxId =  rebackService.getMaxId("OA_yw_实施台账_招标代理管理", "ID_3177");
            int maxId = getMaxId("[ezoffice].[whir$t3177]", "whir$t3177_id");
            /*String sql = String.format(insetSql, maxId+1, projectCode, projectGlobalId, businessName, businessId, ObjectID,
                    noName, tendererName, tenderMethod, tenderCategory1, tenderCategory2, regulators, publishingMedia,
                    otherMedia, governmentBudgetNo, constructionApplicationNo, blocks, acceptanceNumber, biddingAgencyNo);*/
            String sql = String.format(insetSql, maxId+1, projectCode, projectGlobalId, businessCategoryId, businessCategory,
                    noName, tendererName, tenderMethod, tenderCategory1, tenderCategory2, regulators,
                    publishingMedia, otherMedia, governmentBudgetNo, constructionApplicationNo, blocks,
                    acceptanceNumber, biddingAgencyNo, dataSources, businessId, businessName, approvalDate, publicFlag);
            logger.debug("招标代理号新增回写SQL:"+sql);
            flag = performSql(sql);
        } catch (Exception e) {
            saveWriteBackLog(workflowCode, e.toString(), instanceId, "fail");
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 咨询报告号新增回写
     *
     * @param instanceId
     * @return
     */
    public boolean consultingReportNumber(String instanceId, String workflowCode, String reportNo){
        boolean flag = false;
       /* String insetSql = "insert into OA_yw_实施台帐_咨询报告管理 (ID_3424, 项目代码, 业务类别, 业务名称, 报告名称, " +
                "咨询报告号, 项目全局ID, 业务类别全局ID) values('%s', '%s', '%s', '%s', '%s', '%s', '%s')";*/
        String insetSql = "insert into OA_yw_实施台帐_咨询报告管理 (ID_3424, 项目代码, 业务类别, 报告名称, " +
                "咨询报告号, 项目全局ID, 业务类别全局ID, 用印文件类别, 数据来源, 业务ID, 业务名称, 申请日期) values('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')";
        try {
            InstanceData instanceData = new InstanceData(AppUtility.getEngine(), instanceId, User.AdministratorID);
            BizObject bizObject = instanceData.getBizObject();
            //项目代码
            String projectCode = (String)bizObject.GetValue("projectCode");
            //业务类别
            String businessCategory = (String)bizObject.GetValue("businessCategory");
            //业务名称
//            String businessName = (String)bizObject.GetValue("businessName");
            String businessName = (String)bizObject.GetValue("resultDocumentName");
            //报告名称（成果文件名称）
            String resultDocumentName = (String)bizObject.GetValue("resultDocumentName");
            //咨询报告号
            String consultationReportNo = org.apache.commons.lang3.StringUtils.isNotBlank(reportNo)?reportNo:(String)bizObject.GetValue("consultationReportNo");
            //项目全局ID
            String projectGlobalId = (String)bizObject.GetValue("projectGlobalId");
            //业务类别全局ID
            String businessCategoryId = (String)bizObject.GetValue("businessCategoryId");
            //用印文件类别(报告类型)
            String reportType = (String)bizObject.GetValue("reportType");
            //业务ID
            String businessId = (String)bizObject.GetValue("businessId");
            //申请日期
            String approvalDate = WritebackController.clearDefaultDate(DateUtil.format(new Date(), dateFormatStr));
//            int maxId =  rebackService.getMaxId("OA_yw_实施台帐_咨询报告管理", "ID_3424");
            int maxId =  getMaxId("[ezoffice].[whir$t3424]", "whir$t3424_id");
//            String sql = String.format(insetSql, maxId+1, projectCode, businessCategory, businessName, resultDocumentName, consultationReportNo, projectGlobalId, businessId);
            String sql = String.format(insetSql, maxId+1, projectCode, businessCategory, resultDocumentName, consultationReportNo, projectGlobalId, businessCategoryId, reportType, dataSources, businessId, businessName, approvalDate);
            logger.debug("咨询报告号新增回写SQL:"+sql);
            flag = performSql(sql);
        } catch (Exception e) {
            saveWriteBackLog(workflowCode, e.toString(), instanceId, "fail");
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 造价报告号新增回写
     *
     * @param instanceId
     * @return
     */
    public boolean costReportNo(String instanceId, String workflowCode, String reportNo){
        boolean flag = false;
//        String insetSql = "insert into OA_yw_实施台账_造价报告管理 (ID_3327, 项目代码, 项目全局ID, 造价报告号全局ID, " +
//                "业务类别全局ID, 业务类别, 报告类型, 报告名称, 造价报告号) values('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')";
        String insetSql = "insert into OA_yw_实施台账_造价报告管理 (ID_3327, 项目代码, 项目全局ID, 业务类别全局ID," +
                "业务类别, 用印文件类别, 报告名称, 造价报告号, 数据来源, 业务ID, 业务名称, 申请日期) values('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')";
        try {
            InstanceData instanceData = new InstanceData(AppUtility.getEngine(), instanceId, User.AdministratorID);
            BizObject bizObject = instanceData.getBizObject();
            //项目代码
            String projectCode = (String)bizObject.GetValue("projectCode");
            //项目全局ID
            String projectGlobalId = (String)bizObject.GetValue("projectGlobalId");
            //业务类别全局ID
            String businessCategoryId = (String)bizObject.GetValue("businessCategoryId");
            //业务类别
            String businessCategory = (String)bizObject.GetValue("businessCategory");
            //报告类型(用印文件类别)
            String reportType = (String)bizObject.GetValue("reportType");
            //报告名称
            String resultDocumentName = (String)bizObject.GetValue("resultDocumentName");
            //造价报告号
            String costReportNo = org.apache.commons.lang3.StringUtils.isNotBlank(reportNo)?reportNo:(String)bizObject.GetValue("costReportNo");
            //业务ID
            String businessId = (String)bizObject.GetValue("businessId");
            //业务名称
//            String businessName = (String)bizObject.GetValue("businessName");
            String businessName = (String)bizObject.GetValue("resultDocumentName");
            //审批日期
            String approveDate = WritebackController.clearDefaultDate(DateUtil.format(new Date(), dateFormatStr));
//            int maxId = rebackService.getMaxId("OA_yw_实施台账_造价报告管理", "ID_3327");
            int maxId = getMaxId("[ezoffice].[whir$t3327]", "whir$t3327_id");
//            String sql = String.format(insetSql, maxId+1 , projectCode, projectGlobalId, businessName, costReportNoGlobalId, businessCategoryId, businessCategory, reportType, resultDocumentName, costReportNo);
            String sql = String.format(insetSql, maxId+1 , projectCode, projectGlobalId, businessCategoryId,
                    businessCategory, reportType, resultDocumentName, costReportNo, dataSources, businessId, businessName, approveDate);
            logger.debug("造价报告号新增回写SQL:"+sql);
            flag = performSql(sql);
        } catch (Exception e) {
            saveWriteBackLog(workflowCode, e.toString(), instanceId, "fail");
            e.printStackTrace();
        }
        return flag;
    }
}
